<template>
  <div class="demo-warp">
    <Row :gutter="20">
      <Col span="7">
        <Alert>
          <face-feature @feature="getFaceFeature"></face-feature>
        </Alert>
        人脸比对开关
        <i-switch size="large" v-model="faceMatchingSwitch">
          <span slot="open">开启</span>
          <span slot="close">关闭</span>
        </i-switch>
      </Col>
      <Col span="17">
        <Alert type="success">
          人脸比对结果
        </Alert>
        <div class="match-ed">
          <Row :gutter="20">
            <Col span="12" v-for="item in matchEd">
              <div class="item">
                <div class="img">
                  <img :src="item.face_img">
                </div>
                <div class="desc">
                  <p>UID：{{item.uid}}</p>
                  <p>账号：{{item.username}}</p>
                  <p>昵称：{{item.nickname}}</p>
                  <p>相似度：{{item.score}}</p>
                </div>
              </div>
            </Col>
          </Row>
        </div>
      </Col>
    </Row>
  </div>
</template>

<script>
  import faceFeature from '@/common/faceFeature/faceFeature'
  import {FacePairMatching} from '@/common/db/user'
  import {config, deepCopy} from '@/common/utils'
  import {speak} from '../../../sdk/voice/index'
  import {getAccessToken, sendMsg} from '../../../sdk/weixin/work'

  const softconfig = config.get('softconfig')

  export default {
    name: 'demo',
    data() {
      return {
        faceMatchingSwitch: false,
        matchEd: [],
        lastUID: -1,
        face_dat: null
      }
    },
    created() {
      getAccessToken('ww196f50519dcedcc4', '_bhFgd8WiRm5jHtFBQbeIMQ01OvG7GgJfi8yoRZxXeY').then(res => {
        if (res.errcode !== 0) {
          this.$Message.error(`获取access_token失败，${res.errcode}`)
          return
        }
        this.AccessToken = res.access_token
      }).catch(err => {
        this.$Message.error(`获取access_token失败，${err}`)
      })
    },
    methods: {
      getFaceFeature(data) {
        if (!this.faceMatchingSwitch) {
          return
        }
        this.face_dat = data.faceFeatureCopy
      },
      // 比较特征库
      facePairMatching(face_dat) {
        let maxScore = 0
        // 深度拷贝
        let _list = this.$store.state.userList
        _list.forEach((val, index) => {
          FacePairMatching(this.$store.state.hFREngine, val.faceFeature, face_dat, index).then(ret => {
            if (ret.score >= maxScore) {
              maxScore = ret.score
              if (maxScore >= softconfig.threshold / 100) {
                // 比对到人脸后
                if (this.lastUID === val.uid) {
                  return false
                } else {
                  this.lastUID = val.uid
                  val.score = (ret.score * 100).toFixed(4)
                  this.matchEd.push(deepCopy(val))
                  this.sendMsg(_list[index].username, `哈哈哈~~~，${_list[index].nickname}，我有${val.score}%的机率认识你`)
                  speak(_list[index].nickname)
                  setTimeout(() => {
                    this.lastUID = -1
                  }, softconfig.interval * 1000)
                }
              }
            }
          }).catch(e => {
            this.$Message.error(`对比特征库失败，请重试，${e}`)
          })
        })
      },
      sendMsg(touser, content) {
        if (this.AccessToken) {
          let params = {
            touser,
            msgtype: 'text',
            agentid: 1000045,
            text: {
              content
            }
          }
          sendMsg(this.AccessToken, params).then(res => {
            if (res.errcode !== 0) {
              this.$Message.error(`发送消息失败，${res.errcode}`)
            }
          }).catch(err => {
            this.$Message.error(`发送消息失败，${err}`)
          })
        }
      }
    },
    components: {
      faceFeature
    },
    watch: {
      face_dat(val) {
        this.facePairMatching(val)
      }
    }
  }
</script>

<style scoped lang="stylus">
  .demo-warp
    padding 10px

  .match-ed
    width 100%
    height 640px
    overflow-y auto
    overflow-x hidden
    .item
      display flex
      border 1px solid #d7dde4
      padding 10px
      margin-bottom 10px
      .img
        width 120px
        height 120px
        img {
          width 100%
          height 100%
        }
      .desc
        flex 1
        padding-left 10px
        p
          font-size 14px
          margin-bottom 8px
</style>
